package com.example.bigevent.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.bigevent.constant.UserConstant;
import com.example.bigevent.pojo.Result;
import com.example.bigevent.service.IUserService;
import com.example.bigevent.utils.JwtUtil;
import com.example.bigevent.utils.Md5Util;
import com.example.bigevent.utils.ThreadLocalUtil;
import jakarta.validation.constraints.Pattern;
import lombok.extern.slf4j.Slf4j;
import com.example.bigevent.pojo.User;
import org.hibernate.validator.constraints.URL;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @author author
 * @since 2024-05-30
 */
@RestController
@RequestMapping("/user")
@Slf4j
@Validated
public class UserController {
    @Autowired
    private IUserService userService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    /**
     * 用户注册
     * @param username
     * @param password
     * @return
     */
    @PostMapping("/register")
    public Result register(@Pattern(regexp = "^\\S{5,16}$") String username,
                           @Pattern(regexp = "^\\S{5,16}$")String password){
        log.info("用户注册：{},{}",username,password);
        //查询用户是否存在
        User user = userService.getByUsername(username);
        if (user != null){
            //存在，返回已存在
            return Result.error(UserConstant.REGISTER);
        }
        //密码加密
        String md5Password = Md5Util.getMD5String(password);
        //不存在，数据加入数据库,返回注册成功
        User newUser = User.builder().username(username)
                .password(md5Password)
                .createTime(LocalDateTime.now())
                .updateTime(LocalDateTime.now())
                .build();
        userService.save(newUser);
        return Result.success();
    }

    /**
     * 用户登录
     * @param username
     * @param password
     * @return
     */
    @PostMapping("/login")
    public Result<String> add(@Pattern(regexp = "^\\S{5,16}$") String username,
                              @Pattern(regexp = "^\\S{5,16}$")String password){
        log.info("用户登录：{},{}",username,password);
        //查询用户是否存在
        User user = userService.getByUsername(username);
        if (user == null){
            //不存在，返回用户名不存在
            return Result.error(UserConstant.LOGIN);
        }
        //存在，判断密码是否正确
        if (!Md5Util.getMD5String(password).equals(user.getPassword())){
            //密码错误，返回登录失败
            return Result.error(UserConstant.LOGIN);
        }
        Map<String,Object> claims = new HashMap<>();
        claims.put("id",user.getId());
        claims.put("username",user.getUsername());
        String token = JwtUtil.genToken(claims);
        //把token存储到redis中
        ValueOperations<String, String> stringStringValueOperations = stringRedisTemplate.opsForValue();
        stringStringValueOperations.set(token,token,12, TimeUnit.HOURS);
        //密码正确，返回登录成功
        return Result.success(token);
    }

    /**
     * 获取用户详细信息
     * @param
     * @return
     */
    @GetMapping("/userInfo")
    public Result<User> userInfo(/*@RequestHeader(name = "Authorization") String token*/){
        /*//解析token，获取username
        Map<String, Object> map = JwtUtil.parseToken(token);
        String username = (String) map.get("username");*/

        Map<String,Object> map = ThreadLocalUtil.get();
        String username = (String) map.get("username");
        //根据username查询用户详细信息
        User user = userService.getByUsername(username);
        return Result.success(user);
    }

    /**
     * 更新用户基本信息
     * @param user
     * @return
     */
    @PutMapping("/update")
    public Result update(@RequestBody User user){
        userService.updateUserInfo(user);
        return Result.success();
    }

    /**
     * 更新用户头像
     * @param avatarUrl
     * @return
     * a
     */
    @PatchMapping("/updateAvatar")
    public Result updateAvatar(@RequestParam @URL String avatarUrl){
        userService.updateAvatar(avatarUrl);
        return Result.success();
    }

    /**
     * 更新用户密码
     * @param params
     * @return
     */
    @PatchMapping("/updatePwd")
    public Result updatePwd(@RequestBody Map<String,String> params,@RequestHeader("Authorization") String token){
        //集合中获取参数
        String oldPwd = params.get("old_pwd");
        String newPwd = params.get("new_pwd");
        String rePwd = params.get("re_pwd");
        //参数校验
        //判断是否为空
        if (!StringUtils.hasLength(oldPwd) || !StringUtils.hasLength(newPwd) || !StringUtils.hasLength(rePwd) ){
            return Result.error(UserConstant.PWD_NULL);
        }
        //判断原密码是否正确
        Map<String,Object> map = ThreadLocalUtil.get();
        Integer id = (Integer) map.get("id");
        User user = userService.getById(id);
        if (!user.getPassword().equals(Md5Util.getMD5String(oldPwd))){
            return Result.error(UserConstant.ORIGINAL_PWD_ERROR);
        }
        //判断两次密码是否相同
        if (!newPwd.equals(rePwd)){
            return Result.error(UserConstant.RE_PWD);
        }
        userService.updatePwd(newPwd);
        //删除redis中原有的token
        ValueOperations<String, String> stringStringValueOperations = stringRedisTemplate.opsForValue();
        stringStringValueOperations.getOperations()
                .delete(token);
        return Result.success();

    }

}
